package com.taokatao.cardmee.common.widget;


import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

public class TouchBackLayout extends FrameLayout {
    public interface Callback {
        void onTouchBack(View view);
    }


    public TouchBackLayout(Context context) {
        this(context, null);
    }

    public TouchBackLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return isAchieve;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
    }

    private int mWidth, mHeight;
    private long downTimestamp;
    private float downX, downY;
    private boolean isAchieve;
    private Callback callback;

    public void setOnTouchCallback(Callback cb) {
        callback = cb;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return MotionEvent.ACTION_DOWN == ev.getAction() || super.onTouchEvent(ev);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isAchieve = false;
                downTimestamp = System.currentTimeMillis();
                downX = ev.getRawX();
                downY = ev.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (!isAchieve && isEnabled() && downX < mWidth * 0.75) {
                    if (System.currentTimeMillis() - downTimestamp < 300) {
                        if (downY < mHeight * 0.8 && downY > mHeight * 0.2) {
                            float upY = ev.getRawY();
                            if (upY < mHeight * 0.8 && upY > mHeight * 0.2) {
                                float upX = ev.getRawX();
                                if (upX - downX > mWidth * 0.25) {
                                    if (callback != null) callback.onTouchBack(this);
                                    isAchieve = true;
                                }
                            }
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                isAchieve = false;
                break;

        }
        return super.dispatchTouchEvent(ev);
    }
}